﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.WriteAPI.Applications.Commands.CarCommands;
using MediatR;

namespace B.S.BaseData.WriteAPI.Applications.CommandHandlers.CarCommadnHandlers
{
    public class AddCarCommandHandler:IRequestHandler<AddCarCommand,ApiResult<int>>
    {
        IBaseRepository<Domain.Car> carrepository;
        ILogger<AddCarCommandHandler> logger;
        IMapper mapper;

        public AddCarCommandHandler(IBaseRepository<Domain.Car> carrepository,
        ILogger<AddCarCommandHandler> logger,
        IMapper mapper)
        {
            this.carrepository = carrepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddCarCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ApiResult<int>();

                var list = mapper.Map<Domain.Car>(request.data);
                var res = await carrepository.AddAsync(list);
                if(res>0)
                {
                    result.data = res;
                    result.success(res);
                }

                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("车牌添加失败" + ex.Message);
                throw;
            }
        }
    }
}
